package com.hue.concurrent.day03;

/*
    保护性-暂停模式增强：设置等待超时时间
 */
public class Demo05 {
    public static void main(String[] args) {
        GuardedObject guardedObject = new GuardedObject();
        new Thread(() -> {
            System.out.println("t1等待t2的结果...");
            Object response = guardedObject.getResponse(3000);
            System.out.println("t1接收到结果：" + response);
        }).start();

        new Thread(() -> {
            System.out.println("t2正在计算结果...");
            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            guardedObject.setResponse("hello world!");
        }).start();
    }

    /*
       关联两个线程的对象
     */
    public static class GuardedObject {
        private Object response;

        public Object getResponse(long timeout) {
            synchronized (this) {
                //开始时间
                long start = System.currentTimeMillis();
                //已用时间
                long wait = 0;
                while (response == null) {
                    if (wait >= timeout) {  //等待超时
                        break;
                    }
                    try {
                        this.wait(timeout - wait);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    wait = System.currentTimeMillis() - start;
                }
            }
            return response;
        }

        public void setResponse(Object response) {
            synchronized (this) {
                this.response = response;
                this.notifyAll();
            }
        }
    }
}


